package com.yami.shop.api.controller;

import com.yami.shop.bean.model.WxRecord;
import com.yami.shop.service.IWxRecordService;
import io.swagger.annotations.Api;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.cp.api.WxCpService;
import me.chanjar.weixin.cp.bean.kf.*;
import me.chanjar.weixin.cp.bean.kf.msg.WxCpKfLinkMsg;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;
import java.net.URLEncoder;
import java.nio.charset.Charset;
import java.util.List;

@RestController
@RequestMapping("/xcxtkf/creat")
@Api(tags = "客服接口")
@AllArgsConstructor
@Slf4j
public class KefuController {



    private  WxCpService wxCpService;


    private  IWxRecordService iWxRecordService;



    /**
     * 生成客服账号链接
     */
    @PostMapping("/kefu")
    public ResponseEntity<String> kefu(@Valid @RequestBody WxRecord wxRecord) throws Exception {
        log.debug("获取到的订单id为-----------》{}",wxRecord.getId());
        WxCpKfAccountListResp resp = wxCpService.getKfService().listAccount();
        List<WxCpKfAccountListResp.AccountListDTO> accountList = resp.getAccountList();
        WxCpKfAccountLink link = new WxCpKfAccountLink();
        link.setOpenKfid(accountList.get(0).getOpenKfid());
        link.setScene(wxRecord.getId());
        WxCpKfAccountLinkResp wxCpKfAccountLinkResp = wxCpService.getKfService().getAccountLink(link);
        log.info("生成的客服连接地址为------》{}",wxCpKfAccountLinkResp.getUrl()+"&scene_param="+ URLEncoder.encode(wxRecord.getId(), Charset.defaultCharset().toString()));
        return ResponseEntity.ok(wxCpKfAccountLinkResp.getUrl()+"&scene_param="+ URLEncoder.encode(wxRecord.getId(), Charset.defaultCharset().toString()));
    }




    /**
     *  接收客户发来的消息
     */
    @PostMapping("/send")
    public ResponseEntity<String> send(String recordId) throws Exception {

        WxRecord wxRecord = iWxRecordService.getBaseMapper().selectById(recordId);


        WxCpKfMsgSendRequest wxCpKfMsgSendRequest=new WxCpKfMsgSendRequest();
        wxCpKfMsgSendRequest.setToUser("");
        wxCpKfMsgSendRequest.setOpenKfid("");
        wxCpKfMsgSendRequest.setMsgId("");
        wxCpKfMsgSendRequest.setMsgType("");

        WxCpKfLinkMsg wxCpKfLinkMsg=new WxCpKfLinkMsg();
        wxCpKfLinkMsg.setTitle(wxRecord.getTitle());
        wxCpKfLinkMsg.setDesc(wxRecord.getMiaoshu());
        wxCpKfLinkMsg.setUrl(wxRecord.getCardLink());
        wxCpKfLinkMsg.setThumb_media_id("");
        wxCpKfMsgSendRequest.setLink(wxCpKfLinkMsg);

        WxCpKfMsgSendResp wxCpKfMsgSendResp = wxCpService.getKfService().sendMsg(wxCpKfMsgSendRequest);
        return ResponseEntity.ok(wxCpKfMsgSendResp.getMsgId());
    }
}
